package engine;

/**
 * Class for calculating similarity of documents
 * 
 * @author Vika
 * @author ak2765
 */
public class CosineSimilarityCalculator implements SimilarityCalculator {

	/* (non-Javadoc)
	 * @see engine.SimilarityCalculator#calculateSimilarity(engine.FeaturesVector, engine.FeaturesVector)
	 */
	public double calculateSimilarity(FeaturesVector left, FeaturesVector right) {
		double[] leftVector = left.getVectorValues();
		
		double[] rightVector = right.getVectorValues();
		
		double leftTimesRight = 0;
		for (int i = 0; i < leftVector.length; i++) {
			leftTimesRight += leftVector[i] * rightVector[i];
		}

		double moduleLeft = calculateModule(leftVector);
		
		double moduleRight = calculateModule(rightVector);
		
		return leftTimesRight / (moduleLeft * moduleRight);
	}

	/**
	 * @param vector
	 * @return
	 */
	private double calculateModule(double[] vector) {
		double module = 0;
		for (int i = 0; i < vector.length; i++) {
			module += (vector[i] * vector[i]);
		}
		return Math.sqrt(module);
	}

}
